package main

import (
	"github.com/streadway/amqp"
	"log"
)

func failOnError(err error, msg string) {
	if err != nil {
		log.Fatalf("%s: %s", msg, err)
	}
}
func demo1() {
	//1.连接
	conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
	failOnError(err, "Failed to connect to RabbitMQ")
	defer conn.Close()
	//2.获取Channel
	channel, err := conn.Channel()
	failOnError(err, "Failed to open a channel")
	defer channel.Close()
	//3.声明队列
	queue, err := channel.QueueDeclare("hello", false, false, false, false, nil)
	failOnError(err, "Failed to declare a queue")
	//4.获取接受消息的Deliver通道 是一个chan
	msgs, err := channel.Consume(queue.Name, "", true, false, false, false, nil)
	failOnError(err, "Failed to register a consumer")
	forever := make(chan bool)
	go func() {
		for d := range msgs { //等msg close才能结束 ，但是这个demo好像没有实现，send发完，receive会一直阻塞在这里
			log.Printf("Received a message: %s", d.Body)
		}
		forever <- true
	}()
	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	<-forever
	log.Printf(" sending is over ")
}
func main() {
	demo1()
}
